#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: pdk_type_mapping.py 
@version:
@time: 2022/05/30 
"""
import asyncio

from TapUtil.operatefile.use_excel import UtilExcel
from TapClientCore.T01_init_conf.path_conf import PathConf
from TapUtil.operatefile.use_json import jsonfile2python


class PDKTypeMappingExcel(UtilExcel):

    def __init__(self, path):
        super(PDKTypeMappingExcel, self).__init__(path)
        self.load()

    # sheet(source)-> source:[], target:[]
    def pdk_sheet_read(self):
        sheet_name = self.wb.sheetnames
        all_mapping = {}
        for one in sheet_name:
            new = one.replace('PostgreSQL', 'Postgres')
            sheet_split = new.split(' -> ')
            source = sheet_split[0]
            target = sheet_split[1]
            this_mapping = {
                source: [],
                target: []
            }
            row_number = 0
            while True:
                row_number += 1
                _source = self.read_cell_data(one, row_number, 2)
                _target = self.read_cell_data(one, row_number, 4)
                if not _source:
                    break
                this_mapping[source].append(_source)
                this_mapping[target].append(_target)
            all_mapping[new] = this_mapping
        return all_mapping

    def pdk_sheet_read2(self):
        sheet_name = self.wb.sheetnames
        all_mapping = {}
        for one in sheet_name:
            new = one.replace('PostgreSQL', 'Postgres')
            sheet_split = new.split(' -> ')
            source = sheet_split[0]
            target = sheet_split[1]
            this_mapping = {
                source: [],
                target: []
            }
            row_number = 0
            while True:
                row_number += 1
                _source = self.read_cell_data(one, row_number, 3)
                _target = self.read_cell_data(one, row_number, 10)
                if not _source:
                    break
                this_mapping[source].append(_source)
                this_mapping[target].append(_target)
            all_mapping[new] = this_mapping
        return all_mapping

    def pdk_sheet_write_unit(self, sheet_data):
        for sheet in sheet_data:
            self.create_sheet(sheet)
        del self.wb['Sheet']
        for sheet, data in sheet_data.items():
            column = 1
            for k, v in data.items():
                row = 2
                for _v in v:
                    self.write_data(sheet, row, column, _v)
                    row += 1
                if column == 1:
                    self.write_data(sheet, 1, column, f'{k} 单元测试输入')
                if column == 2:
                    self.write_data(sheet, 1, column, f'{k} 单元测试输出')
                if column == 3:
                    self.write_data(sheet, 1, column, f'{k} TM推演输入')
                if column == 4:
                    self.write_data(sheet, 1, column, f'{k} TM推演输出')
                column += 1

    # source2target-> source:[], target:[]
    @staticmethod
    def tapclient_interface_read(path):
        raw_data = jsonfile2python(path)
        result = {}
        for _type, data in raw_data.items():
            for one in data:
                _type_ = {}
                for k, v in one.items():
                    new_source = k.split('2')[0]
                    new_target = k.split('2')[1]
                    tmp = {}
                    for _v in v:
                        try:
                            tmp[_v[0][1]] = _v[1][1]
                        except:
                            pass
                    _type_[k] = tmp
                result.update(_type_)
        return result

    def tapclient_result_add_to_pdk_result(self, tapclient, pdk):
        for pdk_key, pdk_value in pdk.items():
            _source = pdk_key.split(' -> ')[0]
            _target = pdk_key.split(' -> ')[1]
            res = pdk_key.replace(' -> ', '2')

            tapclient_data = tapclient.get(res)

            source_data = pdk_value.get(_source)

            _tmp1 = [f'tap_{_source}']
            _tmp2 = [f'tap_{_target}']
            for one in source_data[1:]:
                flag = 1
                is_list = 0
                list_tmp1 = []
                list_tmp2 = []
                for _one_key, _one_value in tapclient_data.items():
                    if one == _one_key.lower():
                        _tmp1.append(_one_key)
                        _tmp2.append(_one_value)
                        flag = 0
                        break
                    if one in _one_key.lower():
                        list_tmp1.append(_one_key)
                        list_tmp2.append(_one_value)
                        is_list = 1
                if not is_list and flag:
                    _tmp1.append('NOT FOUND')
                    _tmp2.append('NOT FOUND')
                if is_list and flag:
                    _tmp1.append(str(list_tmp1))
                    _tmp2.append(str(list_tmp2))
            pdk_value[f'tap_{_source}'] = _tmp1
            pdk_value[f'tap_{_target}'] = _tmp2
        return pdk

    # excel style execute
    def excel_style(self, find_str='[', style=None):
        sheet_name = self.wb.sheetnames
        for one in sheet_name:
            row_number = 0
            while True:
                row_number += 1
                _source = self.read_cell_data(one, row_number, 2)
                if not _source:
                    break
                self.set_cell_style(one, row_number, 3, find_str, style)
                self.set_cell_style(one, row_number, 4, find_str, style)


if __name__ == '__main__':
    pdk_unit_test = PathConf.TYPE_MAPPING_PDK_RESULT3
    pdk_tap_compare = PathConf.TYPE_MAPPING_PDK_RESULT_COMPARE

    # 读取单元测试结果
    T = PDKTypeMappingExcel(pdk_unit_test)
    from pprint import pprint

    # 按方式2解析单元测试结果
    pdk_read = T.pdk_sheet_read2()
    # 获取最新的接口测试推演结果
    test_result = PathConf.TYPE_MAPPING_JSON_RESULT
    # 读取接口测试推演结果
    res = T.tapclient_interface_read(test_result)

    # 单元测试结果与接口测试结果比对
    new_res_pdk = T.tapclient_result_add_to_pdk_result(res, pdk_read)

    # 更新路径
    T.update_path(pdk_tap_compare)

    # 写入单元测试与接口测试比对结果
    T.pdk_sheet_write_unit(new_res_pdk)

    # style set
    T.excel_style()
    T.excel_style('NOT FOUND', {'fgColor': 'ffff99'})
